#!/bin/bash

# SSL 证书自动配置脚本
echo "🔒 开始配置 SSL 证书..."

DOMAIN="api.xlcig.cn"
EMAIL="your-email@example.com"  # 请替换为你的邮箱

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
}

# 安装 Certbot
install_certbot() {
    log "安装 Certbot..."
    
    if command -v apt &> /dev/null; then
        apt update
        apt install -y certbot
    elif command -v yum &> /dev/null; then
        yum install -y certbot
    else
        error "不支持的操作系统"
        exit 1
    fi
}

# 停止 Nginx 容器
stop_nginx() {
    log "临时停止 Nginx 容器..."
    docker stop xlcig-nginx 2>/dev/null || true
}

# 获取 SSL 证书
get_certificate() {
    log "获取 SSL 证书..."
    certbot certonly --standalone -d $DOMAIN --email $EMAIL --agree-tos --non-interactive
    
    if [ $? -eq 0 ]; then
        log "SSL 证书获取成功"
    else
        error "SSL 证书获取失败"
        exit 1
    fi
}

# 复制证书到项目目录
copy_certificates() {
    log "复制证书到项目目录..."
    
    mkdir -p ssl
    cp /etc/letsencrypt/live/$DOMAIN/fullchain.pem ssl/$DOMAIN.crt
    cp /etc/letsencrypt/live/$DOMAIN/privkey.pem ssl/$DOMAIN.key
    chmod 644 ssl/$DOMAIN.crt
    chmod 600 ssl/$DOMAIN.key
    
    log "证书复制完成"
}

# 重启服务
restart_services() {
    log "重启服务..."
    docker-compose -f docker-compose.server.yml up -d
    log "服务重启完成"
}

# 设置自动续期
setup_auto_renewal() {
    log "设置自动续期..."
    
    # 创建续期脚本
    cat > /usr/local/bin/renew-cert.sh << EOF
#!/bin/bash
certbot renew --quiet
if [ \$? -eq 0 ]; then
    cp /etc/letsencrypt/live/$DOMAIN/fullchain.pem $(pwd)/ssl/$DOMAIN.crt
    cp /etc/letsencrypt/live/$DOMAIN/privkey.pem $(pwd)/ssl/$DOMAIN.key
    docker-compose -f $(pwd)/docker-compose.server.yml restart nginx
fi
EOF

    chmod +x /usr/local/bin/renew-cert.sh
    
    # 添加到 crontab
    (crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/renew-cert.sh") | crontab -
    
    log "自动续期设置完成"
}

main() {
    if [ "$EUID" -ne 0 ]; then
        error "请使用 root 用户运行此脚本"
        exit 1
    fi

    install_certbot
    stop_nginx
    get_certificate
    copy_certificates
    restart_services
    setup_auto_renewal
    
    echo ""
    echo -e "${GREEN}🎉 SSL 证书配置完成！${NC}"
    echo "• 证书路径: ssl/$DOMAIN.crt"
    echo "• 私钥路径: ssl/$DOMAIN.key"
    echo "• 自动续期已设置"
}

main "$@" 